<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of show
 *
 * @author Janis
 */
class Controller_Show extends Controller_Template {
    private $user_data;
    private $user_id;
    private $language;
    
    public function before() {
        $this->language = Cookie::get((Auth::check() ? 'user' : 'guest') . '_language', 'lv');
        Config::set("language", $this->language);
        Lang::load('main', null, $this->language, true);
        
        parent::before();
        $this->user_data = Auth::instance();
        $this->user_id = $this->user_data->get_user_id();
        
        $this->template->language = $this->language;
        $this->template->genres = Model_Orm_Genre::find('all');
        $this->template->cinema_info = Model_Orm_Cinema::find('first');
    }
    
    public function action_add() {
        if(!Auth::member(100)) {
            Response::redirect('/');
        }
        
        if(Input::method() === 'POST') {

            //Checking if show start and end times are valid
            if((int)Input::post("Start_timestamp") >= (int)Input::post("End_timestamp") || $this->existing_shows(Input::post("Start_timestamp"), Input::post("End_timestamp"), Input::post("Auditorium_ID"))) {
                    Session::set_flash('error', 'Kļūda izrādes sākuma vai beigu laikā; auditorijā šajā laikā jau notiek seanss !');
                    Response::redirect('show/add');
            } else {

                $validation = Model_Orm_Show::validate('add');
                if($validation->run()) {
                    
                if(((int)Input::post("End_timestamp") - (int)Input::post("Start_timestamp")) < (int)Input::post("Movie_duration_mins")) {
                    Session::set_flash('error', 'Seansa garums ir īsāks par filmas garumu !');
                    Response::redirect('/show/add');
                }
                    
                    $is_3d = Input::post('Movie_3D');

                    if($is_3d) {
                        $auditorium = Model_Orm_Auditorium::find($validation->validated("Auditorium_ID"));
                        
                        if($auditorium->support_3d == 0) {
                            Session::set_flash('error', 'Šajā auditorijā nevar rādīt 3D filmas !');
                            Response::redirect('/show/add');
                        }
                    }
                    
                    $new_show = new Model_Orm_Show();
                    $new_show->movie_id = $validation->validated("Movie_ID");
                    $new_show->auditorium_id = $validation->validated("Auditorium_ID");
                    $new_show->start_time = $validation->validated("Start_timestamp");
                    $new_show->end_time = $validation->validated("End_timestamp");
                    $new_show->movie_3d = Input::post('Movie_3D') ? 1 : 0;
                    $new_show->language = $validation->validated("Language");
                    $new_show->price = $validation->validated("Price");
                    
                    $new_show->save();
                    
                    Session::set_flash('success', 'Seanss pievienots !');
                } else {
                    Session::set_flash('error', $validation->error());
                 //   Response::redirect('show/add');
                }
            }
        }
        
        $auditorium_nrs = Model_Orm_Auditorium::load_auditoriums();
        
        $view_show_add = View::forge('show/add');
        $view_show_add->set("auditoriums", $auditorium_nrs);
        $this->template->page_custom_scripts = array('datetimepicker.js');
        $this->template->page_content = $view_show_add;
    }
    
    public function action_view($show_id = null) {
        if($show_id === null) {
            $all_shows = Model_Orm_Show::find('all', array('related' => 'movie'));
            
            $content = array();
            
            //Collecting data about all shows.
            foreach($all_shows as $show) {
                $related_data = $show->get('movie');
                $tmp = array("title_lv" => $related_data["title_lv"],
                            "start_time" => date('d.m.Y H:i', $show->start_time),
                            "end_time" => date('d.m.Y H:i', $show->end_time),
                            "duration" => $this->convertTime($related_data["duration"]),
                            "price" => $show->price . " EUR",
                            "auditorium_id" => $show->auditorium_id,
                            "id" => $show->id);
      
                array_push($content, $tmp);
            }
            
            $view_show_viewall = View::forge('show/view_all');
            $view_show_viewall->set('content', $content);
            $this->template->page_content = $view_show_viewall;  
        } else {
            //specific show ?
        }
    }
    
    //Looking for existing shows in specific time and auditorium
    public function existing_shows($start_timestamp, $end_timestamp, $auditorium_id) {
        $existing_shows1 = DB::select()->from('shows')
            ->where('start_time', 'between', array($start_timestamp, $end_timestamp))
            ->or_where('end_time', 'between', array($start_timestamp, $end_timestamp))
            ->execute()->as_array();
        
        $existing_shows2 = DB::select()->from('shows')
            ->where('start_time', '<=', $start_timestamp)
            ->and_where('end_time', '>=', $end_timestamp)
            ->execute()->as_array();
        
        if(count($existing_shows1) != 0 || count($existing_shows2) != 0) {
            //Looking for auditorium "collisions".
            
            foreach($existing_shows1 as $show) {
                if( $show["auditorium_id"] == $auditorium_id) {
                    return true;
                }   
            }
           
            foreach($existing_shows2 as $show) {
                if( $show["auditorium_id"] == $auditorium_id) {
                    return true;
                }   
            }
        }
        
        return false;
    }
    
    public function convertTime($minutes) {
        return floor($minutes/60) . " h ". $minutes % 60 . " min";
    }
    
    public function action_edit($show_id = null) {
        if(!Auth::member(100)) {
            Response::redirect('/');
        }
        
        is_null($show_id) and Response::redirec('/');
        
        $show_data = Model_Orm_Show::find($show_id);
        
        is_null($show_data) and Response::redirect('/');
        
        if(Input::method() === 'POST') {              
            if((int)Input::post("Start_timestamp") >= (int)Input::post("End_timestamp") || $this->existing_shows(Input::post("Start_timestamp"), Input::post("End_timestamp"), Input::post("Auditorium_ID"))) {
                    Session::set_flash('error', 'Kļūda izrādes sākuma vai beigu laikā; auditorijā šajā laikā jau notiek seanss !');
                    Response::redirect('show/edit/'.$show_id);
            } else {
                       
                //Looking for show time conflicts.
                if(((int)Input::post("End_timestamp") - (int)Input::post("Start_timestamp")) < (int)Input::post("Movie_duration_mins")) {
                    Session::set_flash('error', 'Seansa garums ir īsāks par filmas garumu !');
                    Response::redirect('/show/edit/'. $show_id);
                }
                
                $validation = Model_Orm_Show::validate('edit');
                if($validation->run()) {
                    
                    $is_3d = Input::post('Movie_3D');

                    if($is_3d) {
                        $auditorium = Model_Orm_Auditorium::find($validation->validated('Auditorium_ID'));
                        
                        if($auditorium->support_3d == 0) {
                            Session::set_flash('error', 'Norādītajā auditorijā nevar rādīt 3D filmas !');
                            Response::redirect('/show/edit/'. $show_id);
                        }
                    }
                    
                    $show_data->movie_id = $validation->validated("Movie_ID");
                    $show_data->auditorium_id = $validation->validated("Auditorium_ID");
                    $show_data->start_time = $validation->validated("Start_timestamp");
                    $show_data->end_time = $validation->validated("End_timestamp");
                    $show_data->movie_3d = Input::post('Movie_3D') ? 1 : 0;
                    $show_data->language = $validation->validated("Language");
                    $show_data->price = $validation->validated("Price");
                    
                    $show_data->save();
                    
                    Session::set_flash('success', 'Seanss labots !');
                //    Response::redirect('show/add');
                } else {
                //    echo var_dump($validation);
                    Session::set_flash('error', $validation->error());
                 //   Response::redirect('show/add');
                }
            }
        }
        
        $auditorium_nrs = Model_Orm_Auditorium::load_auditoriums();
        $movie_data = Model_Orm_Movie::find($show_data->movie_id);
        
        $view_show_add = View::forge('show/edit');
        $view_show_add->set('auditoriums', $auditorium_nrs);
        $view_show_add->set('show_data', $show_data);
        $view_show_add->set('movie_data', $movie_data);
        $this->template->page_custom_scripts = array('datetimepicker.js');
        $this->template->page_content = $view_show_add;
    }
    
    //Action cancels show.
    public function action_cancel($show_id = null) {
        is_null($show_id) and Response::redirect('/');
        
        $show_data = Model_Orm_Show::find($show_id);
        
        is_null($show_data) and Response::redirect('/');
        
        //Show is cancelled if it is added to a specific auditorium (1st in this case).
        $show_data->auditorium_id = 1;
        $show_data->save();
        
        Session::set_flash('success', 'Seanss atcelts');
        Response::redirect('/show/view/');
    }
}
